package com.xinlu.util.tool;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import org.hibernate.CallbackException;
import org.springframework.beans.BeanUtils;

import com.xinlu.common.exception.CommonException;
import com.xinlu.common.exception.SysException;

public class ReflectUtil {
	
	/**
	 * 
	 * function: 得到类名字 比如RefectUtil
	 * 
	 * @param className
	 *            包名+类名 比如 com.sinyee.util.RefectUtil
	 * @return
	 * 
	 * @author Rain Stars Mar 7, 2009 3:42:58 PM
	 */
	public static String getClassBefine(String className) {

		String doMethodName = null;

		if (className != null) {

			String[] formNames = className.split("\\.");

			if (formNames.length != 0) {
				doMethodName = formNames[formNames.length - 1];
			}

		}

		return doMethodName;
	}
	
	
	/**
	 * 
	 * function:动态执行对象中的方法
	 * 
	 * @param o
	 * @param method
	 * @param parameterTypes
	 * @param parameterValue
	 * @return 执行结果
	 * 
	 * @author Rain Stars Feb 25, 2009 3:25:16 PM
	 */
	public static Object invoke(Object o, String methodName, Class[] parameterTypes, Object[] parameterValue) throws CallbackException {

		Object returnObject = null;

		// 得到类定义
		Class objectClass = o.getClass();

		// 得到doAction对应的方法
		Method method;

		try {

			method = BeanUtils.findMethod(objectClass, methodName, parameterTypes);

			// 无论是什么标示，都可以执行
			method.setAccessible(true);

			// 执行操作
			returnObject = method.invoke(o, parameterValue);

		} catch (Exception e) {

			// 如果是方法操作内的异常
			if (e instanceof InvocationTargetException) {

				InvocationTargetException ex = (InvocationTargetException) e;

				if (ex.getTargetException() instanceof CommonException) {

					CommonException new_name = (CommonException) ex.getTargetException();

					throw new_name;

				} else {

					throw new SysException(ex.getTargetException().getMessage(), ex.getTargetException());
				}

			} else {
				throw new SysException("[" + o.getClass().getName() + "] invoke [" + methodName + "] fail!", e);
			}

		}

		return returnObject;
	}
	
}
